<template>
  <div class="recent-view">
    <!-- 标题 -->
    <div class="recent-view__title">最近查看</div>

    <!-- 卡片网格 -->
    <div class="recent-view__grid">
      <!-- 动态生成卡片 -->
      <div
        v-for="(item, index) in userList"
        :key="index"
        class="card"
        @click="goToDetail(item)"
      >
        <!-- 图片区域 -->
        <div class="card__image-wrapper">
          <img
            class="card__image"
            :data-src="item.geneReport || deflutImage"
            alt="报告图片"
            loading="lazy"
            v-lazy
          />
        </div>

        <!-- 编号与图标 -->
        <div class="card__header">
          <div class="card__header-left">
            <span class="card__basic-id">{{ item.basicId }}</span>

            <!-- 固定图标 -->
            <img
              class="card__icon"
              data-src="/img/ps9dtwpgbaua7m66ivh0f27hwfa63eyj6iiff8c5823.png"
              referrerpolicy="no-referrer"
              loading="lazy"
              v-lazy
            />
            <!-- 条件图标 -->
            <img
              v-if="item.rozenDonation"
              class="card__icon"
              data-src="/img/psijcmo3sgti6l3utq3wx964d33ctervs2152c9896.png"
              referrerpolicy="no-referrer"
              loading="lazy"
              v-lazy
            />
          </div>

          <div class="card__header-right">
            <span class="card__flag-number">{{ item.flagNumber }}</span>
            <img
              class="card__flag-icon"
              data-src="/img/psqzcr9q0kjugojilzr7idrcmlydf7dxjfb85477e7.png"
              loading="lazy"
              v-lazy
            />
            <span class="card__flag-number">{{ item.flagNumber }}</span>
            <img
              class="card__flag-icon"
              data-src="/img/psdbnghkpwnbg38ld11t5wbyq2tnajwarun1c00ad19.png"
              loading="lazy"
              v-lazy
            />
          </div>
        </div>

        <!-- 分隔线 -->
        <div class="divider"></div>

        <!-- 状态 -->
        <div
          class="card__status"
          :class="
            item.available
              ? 'card__status--available'
              : 'card__status--unavailable'
          "
        >
          目前状态：{{ item.available ? "可用" : "不可用" }}
        </div>

        <!-- 详细信息 -->
        <div class="card__details">
          <!-- 年龄 -->
          <div class="detail-row">
            <span class="detail-row__label">年龄</span>
            <span class="detail-row__value">{{ item.age }}</span>
          </div>

          <!-- 身高 -->
          <div class="detail-row">
            <span class="detail-row__label">身高</span>
            <span class="detail-row__value">{{ item.height }}</span>
          </div>

          <!-- 体重 -->
          <div class="detail-row">
            <span class="detail-row__label">体重</span>
            <span class="detail-row__value">{{ item.weight }}</span>
          </div>

          <!-- 血型 -->
          <div class="detail-row">
            <span class="detail-row__label">血型</span>
            <span class="detail-row__value">{{ item.bloodType }}</span>
          </div>

          <!-- 眼睛颜色 -->
          <div class="detail-row">
            <span class="detail-row__label">眼睛颜色</span>
            <span class="detail-row__value">{{ item.eyeColor }}</span>
          </div>

          <!-- 头发颜色 -->
          <div class="detail-row">
            <span class="detail-row__label">头发颜色</span>
            <span class="detail-row__value">{{ item.hairColor }}</span>
          </div>

          <!-- 肤色 -->
          <div class="detail-row">
            <span class="detail-row__label">肤色</span>
            <span class="detail-row__value">{{ item.skinTone }}</span>
          </div>

          <!-- 最高学历 -->
          <div class="detail-row">
            <span class="detail-row__label">最高学历</span>
            <span class="detail-row__value">{{ item.education }}</span>
          </div>

          <!-- 种族 -->
          <div class="detail-row">
            <span class="detail-row__label">种族</span>
            <span class="detail-row__value">{{ item.ethnicity }}</span>
          </div>

          <!-- 身份捐献方式 -->
          <div class="detail-row detail-row--last">
            <span class="detail-row__label">开放身份捐献还是匿名？</span>
            <span class="detail-row__value">{{
              item.anonymous ? "匿名" : "开放身份"
            }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import { useUserStore } from "@/store/modules/user";
import { useRouter } from "vue-router";
import { browsingsList } from "@/api/business/intendedparents";
import deflutImage from "/no.png";

/* -------------------- 响应式数据 -------------------- */
const userStore = useUserStore();
const router = useRouter();
const user_id = ref(userStore.id);

// 用户列表
const userList = ref([]);
// 加载状态
const loading = ref(true);
// 总条数
const total = ref(0);

// 查询参数
const queryParams = reactive({
  userId: user_id.value,
});

/* -------------------- 生命周期 -------------------- */
onMounted(() => {
  getList();
});

/* -------------------- 业务方法 -------------------- */
/** 获取用户列表 */
function getList() {
  loading.value = true;
  browsingsList(queryParams)
    .then((res) => {
      userList.value = res.data;
      total.value = res.data?.length || 0;
    })
    .finally(() => {
      loading.value = false;
      nextTick(lazyLoadImages); // DOM 渲染完再执行懒加载
    });
}

/** 分页大小改变 */
function handleSizeChange(val) {
  queryParams.pageSize = val;
  getList();
}

/** 当前页码改变 */
function handleCurrentChange(val) {
  queryParams.pageNum = val;
  getList();
}

/* -------------------- 工具方法 -------------------- */
/** 跳转至详情页 */
const goToDetail = (item) => {
  router.push({
    path: "/parents/detail",
    query: {
      id: item.donorId,
      userId: item.userId,
    },
  });
};

/* -------------------- 懒加载指令 -------------------- */
const lazyLoadImages = () => {
  if (!window.IntersectionObserver) {
    // 浏览器不支持 IntersectionObserver，直接加载
    document.querySelectorAll("img[data-src]").forEach((img) => {
      img.src = img.dataset.src;
      img.removeAttribute("data-src");
    });
    return;
  }

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const img = entry.target;
          img.src = img.dataset.src;
          img.removeAttribute("data-src");
          observer.unobserve(img);
        }
      });
    },
    { rootMargin: "50px" }
  );

  document
    .querySelectorAll("img[data-src]")
    .forEach((img) => observer.observe(img));
};

// 自定义指令：v-lazy（注册一次即可，这里直接在 setup 内实现）
const vLazy = {
  mounted(el) {
    // 指令本身只做标记，真正的懒加载逻辑由 lazyLoadImages 统一处理
    el.setAttribute("data-lazy", "");
  },
};
</script>

<style lang="scss" scoped>
/* ===================== 基础变量 ===================== */
$border-color: #a2c4e8;
$text-primary: #2b5cab;
$text-secondary: #4d4d4d;
$divider-color: #e6e6e6;
$border-light: #e0e0e0;
$radius: 8px;
$gap: 20px;
$max-width: 364px;

/* ===================== 页面容器 ===================== */
.recent-view {
  &__title {
    font-size: 24px;
    font-weight: bold;
  }

  &__grid {
    margin-top: 20px;
    display: grid;
    gap: $gap;

    /* 响应式列数 */
    grid-template-columns: 1fr;

    @media (min-width: 768px) {
      grid-template-columns: repeat(2, 1fr);
    }

    @media (min-width: 1024px) {
      grid-template-columns: repeat(3, 1fr);
    }
  }
}

/* ===================== 卡片 ===================== */
.card {
  border: 1px solid $border-color;
  border-radius: $radius;
  padding: 20px;
  cursor: pointer;
  transition: box-shadow 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  &__image-wrapper {
    margin-bottom: 16px;
  }

  &__image {
    width: 100%;
    max-width: $max-width;
    height: 200px;
    object-fit: cover;
    border-radius: $radius;
  }

  /* 头部区域 */
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
  }

  &__header-left,
  &__header-right {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  &__basic-id {
    font-size: 24px;
  }

  &__icon {
    width: 22px;
    height: 16px;
  }

  &__flag-number {
    font-size: 16px;
    color: $text-secondary;
  }

  &__flag-icon {
    width: 22px;
    height: 16px;
  }

  /* 分隔线 */
  .divider {
    height: 1px;
    background-color: $divider-color;
    margin: 8px 0;
  }

  /* 状态 */
  &__status {
    margin-top: 20px;
    text-align: center;
    font-size: 16px;

    &--available {
      color: $text-primary;
    }

    &--unavailable {
      color: $text-secondary;
    }
  }

  /* 详细信息 */
  &__details {
    margin-top: 38px;
  }
}

/* ===================== 表格行 ===================== */
.detail-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 8px 0;
  border-bottom: 1px solid $border-light;

  &--last {
    border-bottom: none;
  }

  &__label {
    font-size: 16px;
    color: $text-secondary;
    line-height: 24px;
  }

  &__value {
    font-size: 16px;
    color: $text-primary;
    text-align: right;
    line-height: 24px;
  }
}

.recent-view {
  &__title {
    font-size: 16px;
    font-weight: bold;
    font-family: "Microsoft YaHei", sans-serif;
    color: #2b5cab;
    line-height: 1.5;
  }
}
</style>
